package Servlet;

import Dao.UserDao;
import Model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.json.JSONObject;

import java.io.IOException;

@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 仅处理POST请求，GET请求不做处理A
        response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json"); // 设置响应内容类型为JSON

        // 从请求体中读取JSON数据
        JSONObject jsonRequest = new JSONObject(request.getReader().lines().reduce("", (acc, line) -> acc + line, String::concat));

        String id = jsonRequest.getString("id");
        String password = jsonRequest.getString("password"); // 密码

        int ID = Integer.parseInt(id);
        User model = new User(ID, password);
        HttpSession session = request.getSession(true);
        session.setAttribute("UserID", ID);
        session.setAttribute("UserPassword", password);

        // 构建JSON响应
        JSONObject jsonResponse = new JSONObject();
        if (UserDao.selectExist(model)&&ID!=4001) {
            jsonResponse.put("status", "success");
            jsonResponse.put("message", "登录成功");
            response.getWriter().print(jsonResponse.toString());
        } else if (UserDao.selectExist(model)&&ID==4001){
            jsonResponse.put("status", "more success");
            jsonResponse.put("message", "登录成功");
            response.getWriter().print(jsonResponse.toString());
        }else {
            jsonResponse.put("status", "error");
            jsonResponse.put("message", "登录失败，用户名或密码错误");
            response.getWriter().print(jsonResponse.toString());
        }
    }
}